#include"Comm.hpp"

int main()
{
    Init init;      //提前创建比较好
    key_t k = ftok(PATH_NAME.c_str(), PROJ_ID);
    assert(k != -1);
    Log("获取key值成功", Debug) << "key = " << k << endl;
    //sleep(3);

    int shmid = shmget(k, SIZE, IPC_CREAT | IPC_EXCL | MODE);
    assert(shmid != -1);
    Log("创建共享内存成功", Debug) << "shmid = " << shmid << endl;
    //sleep(3);

    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    assert(*shmaddr != -1);
    Log("共享内存关联成功", Debug) << "shmid = " << shmid << endl;
    //sleep(10);

    int fd = OpenFifo(FIFO_PATH_NAME, READ);        //一个读一个写，别把两个都设为写或读，否则将卡在这

    //for(int i = 0; i < 20; ++i)
    while(true)
    {
        Wait(fd);
        printf("%s\n", shmaddr);
        if(strcmp(shmaddr, "quit") == 0)
            break;
        //sleep(1);
    }


    int ret = shmdt(shmaddr);
    if(ret == -1)
    {
        Log("共享内存去关联失败", Error) << "shmid = " << shmid << endl;
        exit(1);
    }
    Log("共享内存去关联成功", Debug) << "shmid = " << shmid << endl;
    //sleep(3);

    ret = shmctl(shmid, IPC_RMID, nullptr);
    if(ret == -1)
    {
        Log("共享内存段删除失败", Error) << endl;
        exit(2);
    }
    Log("共享内存段删除成功", Debug) << "shmid = " << shmid << endl;
    
    CloseFifo(fd);

    return 0;
}